package com.fly.utils;

import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.fly.bean.Column;

import lombok.extern.slf4j.Slf4j;

/**
 ** 数据库元数据工具
 * 
 */
@Slf4j
public class DbMetaDataUtils
{
    /**
     ** 输出表信息
     * 
     * @throws SQLException
     */
    public static void printTableInfo(DatabaseMetaData databaseMetaData, String catalog)
        throws SQLException
    {
        // 获取表名的结果集
        ResultSet rs = databaseMetaData.getTables(catalog, null, null, new String[] {"TABLE"});
        while (rs.next())
        {
            String tableName = rs.getString("TABLE_NAME");
            log.info("表: {}", tableName);
            printColumnInfo(databaseMetaData, catalog, tableName);
        }
    }
    
    /**
     ** 输出列名、类型、注释
     * 
     * @throws SQLException
     */
    private static void printColumnInfo(DatabaseMetaData databaseMetaData, String catalog, String tableName)
        throws SQLException
    {
        ResultSet rs = databaseMetaData.getColumns(catalog, "%", tableName, "%");
        while (rs.next())
        {
            Column column = new Column().setName(rs.getString("COLUMN_NAME"))
                .setType(rs.getString("TYPE_NAME"))
                .setSize(rs.getInt("COLUMN_SIZE"))
                .setNullable(rs.getBoolean("NULLABLE"))
                .setDigits(rs.getInt("DECIMAL_DIGITS"))
                .setDefaultValue(rs.getString("COLUMN_DEF"))
                .setComment(rs.getString("REMARKS"));
            log.info("{}", column);
        }
    }
}
